﻿using FySystem.AssistantServices;
using FySystem.Net.FyNetConnection;
using FySystem.Net.FyNetConnection.Src;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace FySystem.Net.IOT.RemoteControl
{
    /// <summary>
    /// 通用远控接收端
    /// </summary>
    [Obsolete]
    public class RemoteControlListener
    {
        public IAssistantServiceContext ServiceContext { get; private set; }

        public int Port { get; private set; }

        public Func<StateObjectBase, RemoteCommand, RemoteResult> ReceiveCallback { get; private set; }

        public RemoteControlListener(IAssistantServiceContext serviceContext, int port, Func<StateObjectBase, RemoteCommand, RemoteResult> receiveCallback)
        {
            ServiceContext = serviceContext;
            Port = port;
            ReceiveCallback = receiveCallback;
        }

        public void Start()
        {
            try
            {
                ServiceContext.AddService<FyServer>(Guid.NewGuid().ToString("N")).Configure(service =>
                {
                    FyServer server = (FyServer)service;
                    server.SetIpAddress(IPAddress.Any)
                            .SetPort(Port)
                            .SetReceiveBufferSize(4096)                             //远控消息可能会比较长，所以设大一点
                            .SetSubPackageMode(SubPackageMode.None)
                            .SetExceptionCallback((ex, socket) =>
                            {
                                try
                                {
                                    if (socket != null)
                                        socket.Dispose();
                                }
                                catch (Exception e)
                                {
                                    FyLogContext.Write(e.Message);
                                }
                            })
                            .SetReceiveCallback((server, stateObject, data) =>
                            {
                                try
                                {
                                    string jsn = Encoding.UTF8.GetString(data, 0, data.Length);
                                    RemoteCommand command = JsonSerializer.Deserialize<RemoteCommand>(jsn, new JsonSerializerOptions()
                                    {
                                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                                    });

                                    RemoteResult remoteResult = ReceiveCallback?.Invoke(stateObject, command);

                                    //将远控结果返回给客户端
                                    SendResult(stateObject, remoteResult);
                                }
                                catch { }
                            });
                });
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void SendResult(StateObjectBase stateObject, RemoteResult remoteResult)
        {
            try
            {
                remoteResult = remoteResult == null ? new RemoteResult() : remoteResult;
                string jsn = JsonSerializer.Serialize(remoteResult, new JsonSerializerOptions()
                {
                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });
                byte[] buffer = Encoding.UTF8.GetBytes(jsn);

                stateObject.WorkSocket.Send(buffer);
            }
            catch (Exception ex)
            {
                FyLogContext.Write(ex.Message);
            }
        }
    }
}
